using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Finance.DTO.FinanceUser;
using AnQinFrameWorkAPI.Entity.Finance.Entity;
using AnQinFrameWorkAPI.Entity.Finance.View.FinanceUser;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Finance;

/// <summary>
///     财务用户业务层
/// </summary>
public class FinanceUserService
{
    //数据库
    private readonly DatabaseContext _context;

    //自动映射
    private readonly IMapper _mapper;

    //构造注入
    public FinanceUserService(DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    #region 获取财务用户列表

    public async Task<RequestResponseModel> GetFinanceUserList(FinanceUserSearchDTO financeUserSearchDTO)
    {
        //筛选
        var query = _context.FinanceUser
                .ProjectTo<FinanceUserView>(_mapper.ConfigurationProvider)
                .AsNoTracking().WhereIF(a => a.Code.Contains(financeUserSearchDTO.User),
                    !string.IsNullOrEmpty(financeUserSearchDTO.User))
                .WhereIF(a => a.Name.Contains(financeUserSearchDTO.User),
                    !string.IsNullOrEmpty(financeUserSearchDTO.User))
                .WhereIF(a => a.Email.Contains(financeUserSearchDTO.Email),
                    !string.IsNullOrEmpty(financeUserSearchDTO.Email))
                .WhereIF(a => a.CreateTime > financeUserSearchDTO.StartTime, financeUserSearchDTO.StartTime != null)
                .WhereIF(a => a.CreateTime < financeUserSearchDTO.EndTime, financeUserSearchDTO.EndTime != null)
            ;

        //返回列表
        var financeUserList = await query
            .OrderBy(a => a.CreateTime)
            .Page(financeUserSearchDTO.PageIndex, financeUserSearchDTO.PageSize)
            .ToListAsync();

        //总数据量
        var pageCount = await query.CountAsync();

        //返回数据
        var pageResult = new PageResult<FinanceUserView>(financeUserList, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 新增财务用户

    public async Task<RequestResponseModel> AddFinanceUser(FinanceUserAddDTO financeUserAddDTO)
    {
        //检查编码是否已存在
        if (await _context.FinanceUser.AnyAsync(m => m.Code == financeUserAddDTO.Code))
            return RequestResponse.ErrorRequest("财务用户编码已存在");

        //生成新数据
        var financeUser = _mapper.Map<FinanceUserModel>(financeUserAddDTO);

        financeUser.Id = Guid.NewGuid();
        financeUser.CreateTime = DateTime.Now;

        //新增数据
        _context.FinanceUser.Add(financeUser);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(financeUser.Id, "新增成功");
    }

    #endregion

    #region 更新财务用户

    public async Task<RequestResponseModel> PutFinanceUser(FinanceUserUpdateDTO financeUserUpdateDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.FinanceUser, financeUserUpdateDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("财务用户Id无效");

        //检查编码是否已存在（排除自己）
        if (await _context.FinanceUser.AnyAsync(m => m.Code == financeUserUpdateDTO.Code && m.Id != Guid.Parse(financeUserUpdateDTO.Id)))
            return RequestResponse.ErrorRequest("财务用户编码已存在");

        //编辑数据
        var financeUser = _mapper.Map(financeUserUpdateDTO, query);

        //更新表
        _context.FinanceUser.Update(financeUser);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(financeUserUpdateDTO.Id);
    }

    #endregion

    #region 删除财务用户

    public async Task<RequestResponseModel> DeleteFinanceUser(SingleIdDTO deleteDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.FinanceUser, deleteDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("财务用户Id无效");

        //删除数据
        _context.FinanceUser.Remove(query);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion
}